using System;
using System.Collections.Generic;
using System.Text;

namespace Pixysoft.IO
{
    public class StringLineReader
    {
        private string msg = null;

        private int position = -1;

        private StringLineReader() { }

        public StringLineReader(string msg)
        {
            if (msg == null)
                throw new Exception();

            this.msg = msg;

            position = 0;
        }

        public string ReadLine()
        {
            if (position >= msg.Length)
                return "";

            StringBuilder builder = new StringBuilder();

            char preChar = char.MinValue;
            char curChar = char.MinValue;

            foreach (char c in msg.Substring(position))
            {
                if (preChar == char.MinValue)
                    preChar = c;
                else
                    preChar = curChar;

                curChar = c;

                builder.Append(c.ToString());

                position++;

                if (preChar + curChar == char.Parse("\r") + char.Parse("\n"))
                {
                    builder.Remove(builder.Length - 2, 2);

                    break;
                }

            }

            return builder.ToString();

        }

        public string ReadAll()
        {
            if (position >= msg.Length)
                return "";

            StringBuilder builder = new StringBuilder();

            foreach (char c in msg.Substring(position))
            {
                builder.Append(c.ToString());

                position++;
            }

            return builder.ToString();
        }

        public bool HasMore
        {
            get
            {
                return position >= 0 && position <= msg.Length - 1;
            }
        }

        private void test()
        {
            string ts = "1\r\n2\r\n";

            this.msg = ts;
            position = 0;

            Console.WriteLine(ReadLine());
            Console.WriteLine(ReadLine());
        }
    }
}
